#include <gflags/gflags.h>
#include <brpc/channel.h>
#include <thread>

#include "main.pb.h"

void callback(brpc::Controller* cntl, ::example::EchoResponse* response) {
    std::unique_ptr<brpc::Controller> cntl_guard(cntl);
    std::unique_ptr<example::EchoResponse> resp_guard(response);
    if (cntl->Failed() == true) {
        std::cout << "Rpc调用失败：" << cntl->ErrorText() << std::endl;
        return;
    }
    std::cout << "收到响应: " << response->message() << std::endl;
}

int main()
{
    //初始化通道    
    brpc::ChannelOptions options;
    //设置连接超时时间，-1表示一直等待
    options.connect_timeout_ms = -1;
    //设置等待超时时间，-1表示一直等待 
    options.timeout_ms = -1;
    //请求重试次数
    options.max_retry = 3;
    //协议
    options.protocol = "baidu_std"; 
 
    brpc::Channel channel;
    int ret = channel.Init("127.0.0.1:8080",&options);
    if(ret == -1) {
        std::cout << "初始化失败\n";
        return -1;
    }

    // 创建EchoService_Stub对象，用于rpc调用
    example::EchoService_Stub stub(&channel);
    //rpc开始调用
    example::EchoRequest req;
    example::EchoResponse* rsp = new example::EchoResponse();
    req.set_message("你好 这是测试brpc");
    //Controller 可以追踪 RPC 请求的状态，比如是否超时、是否有错误等。
    //用来管理rpc的调用
    brpc::Controller* cntl = new brpc::Controller();
//    stub.Echo(cntl,&req,rsp,nullptr);
//
//    if(cntl->Failed() == true) {
//        std::cout << "rpc调用失败： " << cntl->ErrorText() << std::endl;
//        return -1;
//    }
//
//    std::cout << "收到响应：" << rsp->message() <<std::endl;
    auto clusure = google::protobuf::NewCallback(callback,cntl,rsp);
    //Echo中第三个参数  ::google::protobuf::Closure* done是给异步调用用的
    stub.Echo(cntl,&req,rsp,clusure); // 异步调用
    std::cout << "异步调用结束!\n";
    std::this_thread::sleep_for(std::chrono::seconds(3));


    return 0;
}